const jwt = require('jsonwebtoken');
const { Module, sequelize } = require('../models');
const { Sequelize, QueryTypes, Op } = require('sequelize');
const { parseMetadata } = require('node-xlsx');

class ModuleService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter = {}) {
		const { title, status, exclude_id, include_id = '', attributes = [], type } = filter;

		let sql = `select ${attributes.length ? attributes.map((d) => `module.${d}`).join(',') : `module.*`} from app_module module
		left join (select parent.id parent_id,group_concat(child.title) titles
			from app_module parent
			join app_module child on find_in_set(parent.id, child.parent_ids)
			group by parent.id) children on module.id=children.parent_id
		where delete_time is null`;

		if (title) {
			sql += ` and (title like ? or children.titles like ?)`;
		}

		if (exclude_id) {
			sql += ` and parent_ids not regexp (${String(exclude_id).split(',').join('|')}) and id not in (${exclude_id})`;
		}

		if (!isNaN(status)) {
			sql += ` and status='${status}'`;
		}
		if (type) sql += ` and type='${type}'`;
		if (include_id !== '') sql += ` and id in(${include_id})`;

		sql += ` order by sort desc,id asc`;

		return await sequelize.query(sql, { replacements: [`%${title}%`, `%${title}%`], type: QueryTypes.SELECT });
	}

	async info(where) {
		return Module.findOne({
			where
		});
	}

	async delete(id) {
		return Module.destroy({
			where: {
				[Op.or]: [{
					id: { [Op.in]: String(id).split(',') }
				}, {
					parent_ids: ''
				}]
			}
		});
	}

	async save(params) {
		const { id, parent_id } = params;

		//await Module.describe().then((params) => Object.keys(params));
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		if (parent_id) {
			const { parent_ids } = await Module.findOne({ where: { id: parent_id } }) || {};
			params.parent_ids = `${parent_ids},${parent_id}`;
		} else {
			params.parent_id = 0;
			params.parent_ids = '0';
		}

		if (id) {
			//获取修改之前的parent_ids
			const { parent_ids } = await Module.findByPk(id);
			//修改所有子集菜单
			await sequelize.query(`update app_module set parent_ids=replace(parent_ids, '${parent_ids},', '${params.parent_ids},') where find_in_set('${id}', parent_ids)`, { type: QueryTypes.UPDATE });

			await Module.update(params, {
				where: {
					id
				}
			});
			return Module.findByPk(id);
		} else {
			delete params.id
			return Module.create(params);
		}
	}
}

exports = module.exports = ModuleService;
